# -*- coding: utf-8 -*-

from odoo import models, fields, api
import urllib2
import urllib
import json


class weiXinPartner(models.Model):
    _inherit = 'res.partner'
    weixins = fields.One2many('weixin.user', 'partner_id', u'微信用户')
    weixinscenes = fields.One2many('weixin.scene', 'partner_id', u'微信二维码')

    # 生成二维码
    @api.one
    def button_barcode(self):
        partner = self
        weixin_scene_obj = self.env['weixin.scene']
        weixin_scene_code = "s_" + str(partner.id)

        request = urllib2.Request("https://arc.mxnet.cn/user/getRcode.do?")
        request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
        data = {"scene": weixin_scene_code}

        response = urllib2.urlopen(request, urllib.urlencode(data))
        response_json = response.read()
        response_data = json.loads(response_json)
        barcode_url = response_data['data']['url']

        has_barcode = fields.Boolean(u'已生成二维码', compute='_has_barcode')
        weixin_scene_id = weixin_scene_obj.create({
            'name': weixin_scene_code,
            'partner_id': partner.id,
            'scence_type': 'partner',
            'path': 'page/index/index',
            'barcode_img_url': barcode_url,
        })

        return
